package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.k3xiangmu.adapter.KHAdapter;
import com.example.administrator.k3xiangmu.adapter.RukuAdapter;
import com.example.administrator.k3xiangmu.entity.CK;
import com.example.administrator.k3xiangmu.entity.KH;
import com.example.administrator.k3xiangmu.entity.RukuEntity;
import com.uuzuche.lib_zxing.activity.CaptureActivity;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HuakaActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private Button tj, tj2;
    private EditText et;
    private String no = "";
    private double ye = 0;
    ProgressDialog dialog;
    ListView lv;
    private List<KH> list = new ArrayList<>();
    private KHAdapter adapter;
    HashSet<String> set = new HashSet();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huaka2);
        setTool();
        setView();
        setListen();
    }

    private void setListen() {
        tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
                UpdateTextTask2 updateTextTask = new UpdateTextTask2(HuakaActivity.this);
                updateTextTask.execute();
            }
        });
        tj2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list.size() == 0) {
                    Toast.makeText(HuakaActivity.this, "花卡数量不能为0", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent i = new Intent(HuakaActivity.this, RukuActivity.class);
                Bundle b = new Bundle();
                KH k = new KH();
                b.putSerializable("list", (Serializable) list);
                String s="";
                for(String s1:set){
                    s+=s1;
                }
                b.putString("zhifu",s);
                i.putExtras(b);
                setResult(55, i);
                finish();
            }
        });
    }

    private void setView() {
        dialog = new ProgressDialog(this);
        tj = (Button) findViewById(R.id.tj);
        tj2 = (Button) findViewById(R.id.tj2);
        et = (EditText) findViewById(R.id.et);
        lv = (ListView) findViewById(R.id.lv);
        adapter = new KHAdapter(list, this);
        lv.setAdapter(adapter);
    }

    private void shoud2(final int i) {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog4, null);


        final EditText et1 = (EditText) layout.findViewById(R.id.et);

        et1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        new AlertDialog.Builder(HuakaActivity.this).setTitle("请输入金额").setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String s1 = et1.getText().toString() + "";

                if (s1.equals("")) {
                    Toast.makeText(HuakaActivity.this, "金额不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                KH k = new KH();
                switch (i) {
                    case 0: k.setNo("现金");
                        k.setStatus(157);
                        k.setName("现金");
                        set.add("现金");
                        break;
                    case 1:k.setNo("银行卡");
                        k.setStatus(158);
                        k.setName("银行卡");
                        set.add("银行卡");
                        break;
                    case 2:k.setNo("支付宝");
                        k.setStatus(159);
                        k.setName("支付宝");
                        set.add("支付宝");
                        break;
                    case 3:k.setNo("微信");
                        k.setStatus(160);
                        k.setName("微信");
                        set.add("微信");
                        break;
                }

                k.setYe(ye);
                k.setFk(Double.parseDouble(et1.getText().toString()));
                for (KH kh : list) {
                    if (kh.getNo().equals(k.getNo())) {
                        kh.setFk(k.getFk());
                        no = "";
                        ye = 0;
                        adapter.notifyDataSetChanged();
                        return;
                    }
                }
                list.add(k);
                adapter.notifyDataSetChanged();
//                        RukuEntity e = new RukuEntity();
//                        e.setNumber(s1);
//                        e.setName(name);
//                        e.setId(number2);
//                        e.setCkid(ckid);
//                        e.setCkname(ckname);
//                        list.add(e);
//                        adapter.notifyDataSetChanged();
                no = "";
                ye = 0;

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                no = "";
                ye = 0;
            }
        }).show();

    }

    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("支付页面");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                                               @Override
                                               public boolean onMenuItemClick(MenuItem item) {
                                                   String msg = "";
                                                   switch (item.getItemId()) {
                                                       case R.id.action_sm:
                                                           msg += "Click edit";
                                                           int yourChoice;

                                                           final String[] items = {"现金", "银行卡", "支付宝", "微信"};

                                                           AlertDialog.Builder singleChoiceDialog =
                                                                   new AlertDialog.Builder(HuakaActivity.this);
                                                           singleChoiceDialog.setTitle("支付方式");
                                                           // 第二个参数是默认选项，此处设置为0
                                                           singleChoiceDialog.setItems(items, new DialogInterface.OnClickListener() {
                                                               @Override
                                                               public void onClick(DialogInterface dialog, final int which) {
                                                                   // which 下标从0开始
                                                                   // ...To-do
                                                                   shoud2(which);
                                                               }
                                                           });
                                                           singleChoiceDialog.show();
                                                           break;

                                                   }


                                                   return true;

                                               }
                                           }

        );
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            if (!no.equals("")) {
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.dialog2, null);
                TextView tv1 = (TextView) layout.findViewById(R.id.kh);
                TextView tv2 = (TextView) layout.findViewById(R.id.ye);
                tv1.setText(no);
                tv2.setText(ye + "");

                final EditText et1 = (EditText) layout.findViewById(R.id.et);

                et1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);


                new AlertDialog.Builder(HuakaActivity.this).setTitle("请输入金额").setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s1 = et1.getText().toString() + "";

                        if (s1.equals("")) {
                            Toast.makeText(HuakaActivity.this, "金额不能为空", Toast.LENGTH_LONG).show();
                            return;
                        } else if (Double.parseDouble(et1.getText().toString()) > ye) {
                            Toast.makeText(HuakaActivity.this, "金额不能超过余额", Toast.LENGTH_LONG).show();
                            return;
                        }
                        KH k = new KH();
                        k.setNo(no);
                        k.setYe(ye);
                        k.setName("huaka");
                        k.setStatus(161);
                        set.add("花卡");
                        k.setFk(Double.parseDouble(et1.getText().toString()));
                        for (KH kh : list) {
                            if (kh.getNo().equals(k.getNo())) {
                                kh.setFk(k.getFk());
                                no = "";
                                ye = 0;
                                adapter.notifyDataSetChanged();
                                return;
                            }
                        }
                        list.add(k);
                        adapter.notifyDataSetChanged();
//                        RukuEntity e = new RukuEntity();
//                        e.setNumber(s1);
//                        e.setName(name);
//                        e.setId(number2);
//                        e.setCkid(ckid);
//                        e.setCkname(ckname);
//                        list.add(e);
//                        adapter.notifyDataSetChanged();
                        no = "";
                        ye = 0;

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        no = "";
                        ye = 0;
                    }
                }).show();

            } else {
                no = "";
                ye = 0;

            }


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {


        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {
            Log.i("xxx", "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");

            String sql = "select * from t_bos200000006entry2 where FText='" + et.getText().toString() + "'";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor

            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                int i = rs.getRow();
                no = rs.getString("FText");
                ye = rs.getDouble("FDecimal");

            }


            rs.close();
            stmt.close();
        } catch (SQLException e) {

            Log.i("xxx", e.toString());


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu2, menu);//加载menu文件到布局
        return true;
    }
}
